<template>
    <inner-layout v-loading="loading">

        <div class="filter-bar clearfix">

            <div class="filter-item">
                <span class="filter-item-title">指数</span>
                <el-select class="filter-item-select" v-model="apiParams.stockIndex" placeholder="请选择" @change="filterData">
                    <el-option
                      v-for="item in stockIndexList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code">
                    </el-option>
                </el-select>
            </div>

            <!-- <div class="filter-item">
                <el-button @click="filterData">确定</el-button>
            </div> -->

            <div class="filter-item" v-if="dataList.date.length > 0 && dataList.date.length == dataList.val.length">
                <i class="el-icon-info"></i>
                {{ dataList.date[dataList.date.length - 1] }}：{{ (dataList.val[dataList.val.length - 1] * 1).toFixed(2) }}
            </div>

        </div>

        <div id="chartObj" class="charts-wrap"></div>

        <div class="tip-wrap">
            <div><i class="el-icon-info"></i>比值 = 1 / 指数PE / 16国债19YTM</div>
            <div class="fr"><a href="https://funddb.cn/site/fed" target="_blank">去韭圈儿查看详情&gt;&gt;</a></div>
        </div>

    </inner-layout>
</template>

<script>
import { getXueqiuSh019547, getXueqiuCookieByCache, getXueqiuSh019547Ytm } from '@/api/xueqiu'
import { getDjIndexEvaDetail } from '@/api/danjuanapp'
import { parseTime } from '@/utils/index'
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
export default {
	name: 'NationalDebtVsStockIndex',
	components: { },
    directives: { },
	mixins: [],
	data() {
		return {
			loading: false,
            nationalDebtList: null,
			dataList: {
                date: [],
                val:[],
            },
            apiParams: {
                stockIndex: 'SH000852',
            },
            stockIndexList: [
                {code: 'SH000016', name: '上证50'},
                {code: 'SH000300', name: '沪深300'},
                {code: 'SH000905', name: '中证500'},
                {code: 'SH000852', name: '中证1000'},
                {code: 'SZ399006', name: '创业板'},
                {code: 'SH000688', name: '科创50'},
            ],
            chart: null
		}
	},
	created() {
        console.log('getPageData', getXueqiuCookieByCache())
	},
    mounted() {
        setTimeout(() => {
            this.getPageData()
        }, 1500)
    },
    beforeDestroy() {
    	if (!this.chart) {
    		return
    	}
    	this.chart.dispose()
    	this.chart = null
    },
	methods: {
        getPageData() {
            let that = this

            // console.log('getPageData', getXueqiuCookieByCache())
            // return

            getDjIndexEvaDetail(that.apiParams.stockIndex, 'pe', '5y').then(res1 => {
                let _data1 = res1.data
                if (_data1.result_code === 0) {
                    if (!that.nationalDebtList) {
                        getXueqiuSh019547().then(res => {
                            let _data = res.data
                            if (_data.error_code === 0) {
                                // console.log('getXueqiuSh019547DemoData', _data)
                                let _dateKey = 0
                                let _valKey = 5
                                for (let i in _data.data.column) {
                                    if (_data.data.column[i] == 'timestamp') {
                                        _dateKey = i * 1
                                    } else if (_data.data.column[i] == 'close') {
                                        _valKey = i * 1
                                    }
                                }
                                // debugger
                                that.nationalDebtList = {}
                                _data.data.item.forEach(row => {
                                    that.nationalDebtList[row[_dateKey]] = getXueqiuSh019547Ytm(row[_dateKey], row[_valKey])
                                })
                                // console.log('that.dataList', that.dataList)
                                that.genCharts(_data1.data['index_eva_pe_growths'])
                            } else {
                                that.$message.error('[' + _data.error_code + ']' + (_data.error_description || '获取国债数据失败'))
                            }
                        })
                    } else {
                        that.genCharts(_data1.data['index_eva_pe_growths'])
                    }
                } else {
                    that.$message.error('[' + _data1.result_code + ']获取指数数据失败')
                }
            })
        },
        filterData() {
            this.getPageData()
        },
        genCharts(data1) {
            let that = this

            if (!data1 || data1.length <= 0) {
                that.$message.error('获取数据失败')
                return
            }
            
            that.dataList.date = []
            that.dataList.val  = []

            let _dataList1 = {}
            // debugger
            data1.forEach(row => {
                _dataList1[row.ts] = row['pe']
            })

            Object.keys(_dataList1).forEach(key => {
                if (that.nationalDebtList[key]) {
                    that.dataList.val.push(1 / _dataList1[key] / that.nationalDebtList[key] * 100)
                    that.dataList.date.push(parseTime(key, '{y}-{m}-{d}'))
                }
            })
            console.log('that.dataList', that.dataList)
            that.setOptions()
        },
        setOptions() {
            let that = this
            if (!that.chart) {
                that.chart = echarts.init(document.getElementById('chartObj'))
            }
            that.chart.setOption({
                title: {
                    show: false
                },
                tooltip: {
                	trigger: 'axis',
                	axisPointer: {
                		type: 'cross'
                	},
                	padding: [5, 10]
                },
                xAxis: {
                    data: that.dataList.date
                },
                yAxis: {
                    scale: true
                },
                series: [
                    {
                        name: '股债比',
                        type: 'line',
                        data: that.dataList.val,
                        itemStyle: {
                        	normal: {
                        		color: '#3888fa',
                        		lineStyle: {
                        			color: '#3888fa',
                        			width: 1
                        		}
                        	}
                        },
                        markLine : {
                            data : [
                                {type : 'average', name: '平均值'}
                            ]
                        }
                    },
                ]
            })
        }
	}
}
</script>

<style lang="scss" scoped>
    .filter-item {
        .filter-item-title {
            margin-right: 5px;
        }
        .filter-item-select {
            width: 150px;
        }
    }
    .charts-wrap {
        max-width: 100%;
        height: calc(100vh - 350px);
    }
    .tip-wrap {
        padding: 30px 0;
        font-size: 13px;
        line-height: 26px;
    }
</style>
